package me.zk.practice1.s;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class LS144 {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        get(root,list);
        return list;
    }

    public void get(TreeNode node, List<Integer> list) {
        if (node == null) {
            return;
        }
        list.add(node.val);
        get(node.left,list);
        get(node.right,list);

    }

    public List<Integer> preorderTraversal2(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        getList(root,list);
        return list;
    }
    //根 左右
    public void getList(TreeNode node,List<Integer> list) {
        Stack<TreeNode> stack = new Stack<>();
        while (node != null || !stack.isEmpty()){
            //将左节点存如栈中
            while (node != null) {
                //添加根节点
                list.add(node.val);
                stack.push(node);
                node = node.left;
            }
            TreeNode curr = stack.pop();
            //判断右节点
            if (curr.right != null) {
                node = curr.right;
            }
        }
    }
}
